<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      /* 
        二叉树的层序遍历依靠队列的方式，从左到右，先进先出
        */
      let tree = {
        val: 1,
        left: {
          val: 2,
          left: {
            val: 4,
          },
          right: {
            val: 5,
          },
        },
        right: {
          val: 3,
          left: {
            val: 6,
          },
          right: {
            val: 7,
          },
        },
      }
      /*       var levelOrder = function (root) {
        if (!root) return []
        let res = []
        let queue = [root]
        while (queue.length) {
          //添加新的一层
          res.push([])
          //记录该层节点的数量
          let len = queue.length
          for (let i = 0; i < len; i++) {
            let node = queue.shift()
            res[res.length - 1].push(node.val)
            if (node.left) {
              queue.push(node.left)
            }
            if (node.right) {
              queue.push(node.right)
            }
          }
        }
       return res
      }
      levelOrder(tree) */
      var levelOrder = function (root) {
        if (!root) return []
        let res = []
        let queue = [root]
        while (queue.length) {
          //添加新的一层
          res.push([])
          //记录该层节点的数量
          let len = queue.length
          for (let i = 0; i < len; i++) {
            let node = queue.shift()
            //最后一层的[5,6,7,8]进入循环，这时候node依然存在，依然会push node.left只不过是null而已
            if (node) {
              res[res.length - 1].push(node.val)
              queue.push(node.left)
              queue.push(node.right)
            }
          }
        }
        console.log(res)
      }
      levelOrder(tree)
    </script>
  </body>
</html>
